package com.dao;

import com.entity.Userinfo;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.List;

public class UserInfoDao {

    public void save(Userinfo userinfo) {
        //获取加载配置管理类
        Configuration configuration = new Configuration();
        //不给参数就默认加载hibernate.cfg.xml文件，
        configuration.configure();
        //创建Session工厂对象
        SessionFactory factory = configuration.buildSessionFactory();
        //得到Session对象
        Session session = factory.openSession();
        //使用Hibernate操作数据库，都要开启事务,得到事务对象
        Transaction transaction = session.getTransaction();
        //开启事务
        transaction.begin();
        //把对象添加到数据库中
        session.save(userinfo);
        //提交事务
        transaction.commit();
        //关闭Session
        session.close();
    }

    public Userinfo searchById(Integer id) {
        //获取加载配置管理类
        Configuration configuration = new Configuration();
        //不给参数就默认加载hibernate.cfg.xml文件，
        configuration.configure();
        //创建Session工厂对象
        SessionFactory factory = configuration.buildSessionFactory();
        //得到Session对象
        Session session = factory.openSession();
        Userinfo userinfo = session.get(Userinfo.class, id);
        return userinfo;
    }

    public List<Userinfo> searchList(String sql) {
        //获取加载配置管理类
        Configuration configuration = new Configuration();
        //不给参数就默认加载hibernate.cfg.xml文件，
        configuration.configure();
        //创建Session工厂对象
        SessionFactory factory = configuration.buildSessionFactory();
        //得到Session对象
        Session session = factory.openSession();
        SQLQuery sqlQuery = session.createSQLQuery(sql).addEntity(Userinfo.class);
        return sqlQuery.list();
    }

    public List<Userinfo> searchListByParams(String sql) {
        //获取加载配置管理类
        Configuration configuration = new Configuration();
        //不给参数就默认加载hibernate.cfg.xml文件，
        configuration.configure();
        //创建Session工厂对象
        SessionFactory factory = configuration.buildSessionFactory();
        //得到Session对象
        Session session = factory.openSession();
        SQLQuery sqlQuery = session.createSQLQuery(sql).addEntity(Userinfo.class);
        return sqlQuery.list();
    }
}
